import puppeteer from "puppeteer";
import {
  reportLog,
  waitForTimeout,
  getSiblingsElByTagName,
} from "../utils/index.js";

const requestHeadersToRemove = [
  "host",
  "user-agent",
  "accept-encoding",
  "content-length",
  "forwarded",
  "x-forwarded-proto",
  "x-forwarded-for",
  "x-cloud-trace-context",
];
const responseHeadersToRemove = [
  "Accept-Ranges",
  "Content-Length",
  "Keep-Alive",
  "Connection",
  "content-encoding",
  "set-cookie",
];

// 测试 申报 流程
export const apply = async (userInfo) => {
  await waitForTimeout(3000);

  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();

  await page.setViewport({ width: 1920, height: 1024 });
  await page.removeAllListeners("request");

  page.goto("https://www.pmi.org/account-login?returnUrl=%23RETURNURL%", {
    timeout: 60000,
    waitUntil: "domcontentloaded",
  });

  await page.waitForSelector("#login_btn", { timeout: 60000 }); // 等待验证码弹窗

  console.log(userInfo.index, "登录");

  await page.type('input[name="Username"]', userInfo.pmp_account); // 用户名

  await waitForTimeout(1000);

  await page.type('input[name="Password"]', userInfo.pmp_password); // 密码

  await waitForTimeout(1000);

  await page.click("#login_btn"); // 点击登录

  await waitForTimeout(1000);

  // const client = await page.target().createCDPSession();
  // await client.send("Network.setRequestInterception", {
  //   patterns: [
  //     {
  //       urlPattern: "*",
  //       resourceType: "Document",
  //       interceptionStage: "HeadersReceived",
  //     },
  //   ],
  // });

  page.goto("https://www.pmi.org/", {
    timeout: 60000,
    waitUntil: "domcontentloaded",
  });

  return;

  // 监听页面导航事件
  page.on("navigation", async (navigationEvent) => {
    console.log("页面跳转到：", navigationEvent.url);
  });

  // 设置导航超时时间为60秒
  await page.setDefaultNavigationTimeout(300000);

  // 在页面中注册方法
  page.exposeFunction("getSiblingsElByTagName", getSiblingsElByTagName);

  await page.setUserAgent(
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
  );

  await page.setExtraHTTPHeaders({
    "Upgrade-Insecure-Requests": "1",
    "Sec-Fetch-User": "?1",
    "Sec-Ch-Ua": `"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"`,
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": "Windows",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "none",
    "User-Agent":
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
  });

  // 访问表单页面
  await page.setViewport({ width: 1920, height: 1024 });

  page.goto("https://www.pmi.org/account-login?returnUrl=%23RETURNURL%23");

  await page.waitForSelector("#login_btn", { timeout: 60000 }); // 等待验证码弹窗

  console.log(userInfo.index, "登录");

  await page.type('input[name="Username"]', userInfo.pmp_account); // 用户名

  await waitForTimeout(1000);

  await page.type('input[name="Password"]', userInfo.pmp_password); // 密码

  await waitForTimeout(1000);

  await page.click("#login_btn"); // 点击登录

  await page.setUserAgent(
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
  );

  await page.setExtraHTTPHeaders({
    "Upgrade-Insecure-Requests": "1",
    "Sec-Fetch-User": "?1",
    "Sec-Ch-Ua": `"Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"`,
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": "Windows",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "none",
    "User-Agent":
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
  });

  await page.goto("http://localhost:3000/?url=https://www.pmi.org/");

  const content = await page.content();

  console.log(content);

  // // 获取页面的HTML内容;
  // const errorList = await page.evaluate(() => {
  //   let errorList = [];
  //   let errorText = "";
  //   let errorElList = document.querySelectorAll(".validation-summary-errors");
  //   errorElList.forEach((errorEl) => {
  //     if (errorEl.style.display !== "none") {
  //       let question = getSiblingsElByTagName(errorEl, "label")
  //         ? getSiblingsElByTagName(errorEl, "label").innerText
  //         : "";
  //       let description = errorEl.innerText;
  //       errorList.push({
  //         question,
  //         description,
  //       });
  //       errorText += `${question};${description};`;
  //     }
  //   });
  //   return errorList;
  // });

  // if (errorList.length > 0) {
  //   // 有错误
  //   reportLog("申报失败", {
  //     message: "账号密码错误",
  //     error: errorList,
  //     username: userInfo.username,
  //     index: userInfo.index,
  //   });
  // } else {
  //   // 登录成功;
  // }

  await waitForTimeout(100000);

  // await browser.close();
};
